<template>
    <!--会员列表-->
    <div class="main-container">
        <el-card class="box-card !border-none" shadow="never">

            <div class="flex justify-between items-center">
                <span class="text-page-title">{{ pageName }}</span>
                <el-button type="primary" @click="addEvent">{{ t('addMember') }}</el-button>
            </div>

            <el-card class="box-card !border-none my-[20px] table-search-wrap" shadow="never">
                <el-form :inline="true" :model="memberTableData.searchParam" ref="searchFormRef">
                    <el-form-item :label="t('memberInfo')" prop="keyword">
                        <el-input v-model.trim="memberTableData.searchParam.keyword" class="!w-[200px]" clearable :placeholder="t('memberInfoPlaceholder')" @keyup.enter="loadMemberList()" />
                    </el-form-item>
                    <el-form-item :label="t('cityName')" prop="city">
                        <el-input v-model.trim="memberTableData.searchParam.city" class="!w-[200px]" clearable :placeholder="t('cityNamePlaceholder')" @keyup.enter="loadMemberList()" />
                    </el-form-item>

                    <el-form-item :label="t('registerChannel')" prop="register_channel">
                        <el-select v-model="memberTableData.searchParam.register_channel" clearable :placeholder="t('channelPlaceholder')" class="input-width">
                            <el-option :label="t('selectPlaceholder')" value="" />
                            <el-option :label="item" :value="key" v-for="(item, key) in channelList" :key="key" />
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="t('memberLabel')" prop="member_label">
                        <el-select v-model="memberTableData.searchParam.member_label" collapse-tags clearable :placeholder="t('memberLabelPlaceholder')" class="input-width">
                            <el-option :label="t('selectPlaceholder')" value="" />
                            <el-option :label="item['label_name']" :value="item['label_id']" v-for="(item, index) in labelSelectData" :key="index" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="用户类型" prop="user_type">
                        <el-select v-model="memberTableData.searchParam.user_type" clearable placeholder="请选择用户类型" class="input-width" @change="clearFields">
                            <el-option :label="item.label" :value="item.value" v-for="(item, index) in userTypeList" :key="index" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="memberTableData.searchParam.user_type == 'consumeuser'" label="消费区间" prop="min_max">
                        <el-select v-model="memberTableData.searchParam.min_max" clearable placeholder="请选择消费区间" class="input-width">
                            <el-option :label="item.label" :value="item.value" v-for="(item, index) in consumptionList" :key="index" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="['consumeuser', 'notfenxianguser'].includes(memberTableData.searchParam.user_type)" label="日期范围" prop="day">
                        <el-select v-model="memberTableData.searchParam.day" clearable placeholder="请选择范围" class="input-width">
                            <el-option :label="item.label" :value="item.value" v-for="(item, index) in dayList" :key="index" />
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item :label="t('memberLevel')" prop="member_level">
                        <el-select v-model="memberTableData.searchParam.member_level" collapse-tags clearable :placeholder="t('memberLevelPlaceholder')" class="input-width">
                            <el-option :label="t('selectPlaceholder')" value="" />
                            <el-option :label="item['level_name']" :value="item['level_id']" v-for="(item, index) in levelSelectData" :key="index" />
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="t('createTime')" prop="create_time">
                        <el-date-picker v-model="memberTableData.searchParam.create_time" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" clearable :start-placeholder="t('startDate')" :end-placeholder="t('endDate')" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="loadMemberList()">{{ t('search') }}</el-button>
                        <el-button @click="resetForm(searchFormRef)">{{ t('reset') }}</el-button>
                        <el-button type="primary" @click="exportEvent">{{ t('export') }}</el-button>
                        
                        <el-button type="primary" @click="openImportDialog" class="ml-[12px]">批量上传</el-button>
                    </el-form-item>
                </el-form>
            </el-card>

            <div class="mt-[10px]">
                <div class="mb-[10px] flex items-center">
                    <el-dropdown class="mr-[20px] !text-primary">
                        <span class="el-dropdown-link">
                            <span>{{ currentSelectMode === 'all' ? t('全选所有页') : t('全选当前页')}}</span>({{ selectedCount }})
                            <el-icon>
                                <arrow-down />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item class="select-wrap" :class="{ active: currentSelectMode === 'all' }" @click="selectAllPages">全选所有页</el-dropdown-item>
                                <el-dropdown-item class="select-wrap"  :class="{ active: currentSelectMode === 'page' }" @click="toggleChange">全选当前页</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button @click="batchSetLabel" size="small">{{ t('标签') }}</el-button>
                    <el-button @click="batchSetLevel" size="small">{{ t('等级') }}</el-button>
                </div>
                <el-table :data="memberTableData.data" size="large" ref="memberListTableRef" v-loading="memberTableData.loading" :row-key="(row: any) => row.member_id" :default-selection="defaultSelection" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
                    <template #empty>
                        <span>{{ !memberTableData.loading ? t('emptyData') : '' }}</span>
                    </template>
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="member_no" :label="t('memberNo')" min-width="120" />
                    <el-table-column prop="username" :show-overflow-tooltip="true" :label="t('username')" min-width="200">
                        <template #default="{ row }">
                            <div class="flex items-center">
                                <div class="mr-[10px] rounded-full w-[50px] h-[50px] flex items-center justify-center">
                                    <img class="max-w-[50px] max-h-[50px]" v-if="row.headimg" :src="img(row.headimg)" alt="">
                                    <img class="max-w-[50px] max-h-[50px]" v-else src="@/app/assets/images/member_head.png" alt="">
                                </div>
                                <div class="flex flex-col">
                                    <span v-if="row.username">{{ row.username || '' }}</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column prop="nickname" :show-overflow-tooltip="true" :label="t('nickname')" min-width="130" /> -->
                    <el-table-column prop="mobile" :label="t('mobile')" min-width="120" />
                    <el-table-column prop="member_level_name" :label="t('memberLevel')" min-width="130" :show-overflow-tooltip="true" />
                    <el-table-column label="升级详情" min-width="130" :show-overflow-tooltip="true">
                        <template #default="{ row }">
                            <el-button type="primary" link @click="upgradeDetailEvent(row)">查看</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gold_coupon" :label="t('goldCoupon')" min-width="130" align="right" sortable="custom" />
                    <el-table-column prop="contribution_points" :label="t('contributionPoints')" min-width="130" align="right" sortable="custom" />
                    <el-table-column prop="available_points" :label="t('availablePoints')" min-width="130" align="right" sortable="custom" />
                    <el-table-column prop="balance" :label="t('balance')" min-width="130" align="right" sortable="custom" />
                    <el-table-column prop="digital_asset" :label="t('digitalAsset')" min-width="130" align="right" sortable="custom" />
                    <el-table-column prop="member_label" :label="t('memberLabelTag')" min-width="120" align="center">
                        <template #default="{ row }">
                            <div class="flex flex-col items-center">
                                <div v-for="(item, key) in row.member_label_array" class="my-[3px]" :key="key">
                                    <el-tag type="info">{{ item.label_name }}</el-tag>
                                </div>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="register_channel_name" :label="t('registerChannel')" min-width="110" align="center" />

                    <el-table-column prop="member_label" :label="t('status')" min-width="120" align="center">
                        <template #default="{ row }">
                            <el-tag type="success" v-if="row.status == 1" class="cursor-pointer">{{ t('normal') }}</el-tag>
                            <el-tag type="error" v-else class="cursor-pointer">{{ t('lock') }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="city" :label="t('cityName')" min-width="110" align="center" />
                    <el-table-column :label="t('createTime')" min-width="150" align="center">
                        <template #default="{ row }">
                            {{ row.create_time || '' }}
                        </template>
                    </el-table-column>
                    <el-table-column :label="t('lastVisitTime')" min-width="150" align="center">
                        <template #default="{ row }">
                            {{ row.last_visit_time || '' }}
                        </template>
                    </el-table-column>

                    <el-table-column :label="t('operation')" align="right" fixed="right" width="280">
                        <template #default="{ row }">
                            <div class="flex items-center">
                                <el-button type="primary" link @click="detailEvent(row)">{{ t('detail') }}</el-button>
                                <el-button type="primary" link @click="setMemberLabel(row)">{{ t('setLabel') }}</el-button>
                                <el-button type="warning" link @click="resetPasswordEvent(row)">{{ t('resetPassword') }}</el-button>
                                <el-button type="warning" v-if="row.status == 1" link @click="lockMember(row, 0)">{{ t('lock') }}</el-button>
                                <el-button type="warning" v-else link @click="lockMember(row, 1)">{{ t('unlock') }}</el-button>
                                <el-button type="danger" link @click="deleteEvent(row)">{{ t('memberDelete') }}</el-button>
                            </div>
                        </template>
                    </el-table-column>

                </el-table>
                <div class="mt-[16px] flex justify-end">
                    <el-pagination v-model:current-page="memberTableData.page" v-model:page-size="memberTableData.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="memberTableData.total"
                        @size-change="loadMemberList()" @current-change="loadMemberList" />
                </div>
            </div>
            <add-member ref="addMemberDialog" @complete="loadMemberList()" />
            <edit-member ref="editMemberDialog" @complete="loadMemberListReset()" />
            <export-sure ref="exportSureDialog" :show="flag" type="member" :searchParam="memberTableData.searchParam" @close="handleClose" />
            <detail-member ref="detailMemberDialog"  @load="loadMemberList()"></detail-member>
            
            <!-- 批量上传弹窗 -->
            <el-dialog v-model="importDialog" :title="t('batchImport')" width="420px">
                <div>
                    <el-form :model="importData" label-width="80px" label-position="left">
                        <el-form-item :label="t('uploadFile')" prop="url">
                            <upload-file v-model="importData.url" api="sys/document/excel" />
                        </el-form-item>
                        <div class="form-tip mt-[5px] cursor-pointer !text-[var(--el-color-primary)]" @click="downloadTemplate">
                            {{ t('downloadTemplate') }}
                        </div>
                    </el-form>
                    <div class="mt-[16px]">
                        <div v-for="(item, key) in failList" :key="key">
                            {{ item }}
                        </div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button v-if="failList.length == 0" type="primary" :loading="importDialogLoading" @click="importMember">{{ t('confirm') }}</el-button>
                        <el-button @click="importDialog = false">{{ t('cancel') }}</el-button>
                    </span>
                </template>
            </el-dialog>
            
            <!-- 重置密码弹窗 -->
            <el-dialog v-model="resetPasswordDialog.visible" :title="t('resetPassword')" width="500px" :close-on-click-modal="false">
                <el-form ref="resetPasswordFormRef" :model="resetPasswordDialog.form" :rules="resetPasswordDialog.rules" label-width="120px">
                    <el-form-item :label="t('newPassword')" prop="password">
                        <el-input v-model="resetPasswordDialog.form.password" type="password" :placeholder="t('pleaseEnterNewPassword')" show-password />
                    </el-form-item>
                    <el-form-item :label="t('confirmPassword')" prop="confirmPassword">
                        <el-input v-model="resetPasswordDialog.form.confirmPassword" type="password" :placeholder="t('pleaseConfirmPassword')" show-password />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="resetPasswordDialog.visible = false">{{ t('cancel') }}</el-button>
                        <el-button type="primary" @click="confirmResetPassword" :loading="resetPasswordDialog.loading">{{ t('confirm') }}</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
        <upgrade-detail ref="upgradeDetailDialog" />
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed, onMounted } from 'vue'
import { t } from '@/lang'
import { img } from '@/utils/common'
import { getRegisterChannelType, getMemberList, getMemberLabelAll, editMemberStatus, memberDelAccount, getMemberLevelAll, getMemberRechargePassword, batchImportMember } from '@/app/api/member'
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import AddMember from '@/app/views/member/components/add-member.vue'
import detailMember from '@/app/views/member/components/detail-member.vue'
import EditMember from '@/app/views/member/components/edit-member.vue'
import UploadFile from '@/components/upload-file/index.vue'
import UpgradeDetail from '@/app/views/member/components/upgrade-detail.vue'

const route = useRoute()
const pageName = route.meta.title

const memberTableData = reactive<any>({
    page: 1,
    limit: 10,
    total: 0,
    loading: true,
    data: [],
    searchParam: {
        keyword: '',
        city: '',
        register_type: '',
        member_label: '',
        register_channel: '',
        create_time: [],
        member_level: '',
        order: '',
        type: '',
        user_type: '',
        day: '',
        min_max: '',
    }
})
const userTypeList = ref([
    { label: '消费用户', value: 'consumeuser' },
    { label: '复购人员', value: 'byconsumeuser' },
    { label: '未推广人员', value: 'notfenxianguser' }
])

const dayList = ref([
    { label: '7天', value: 7 },
    { label: '15天', value: 15 },
    { label: '30天', value: 30 },
    { label: '180天', value: 180 },
])

const consumptionList = ref([
    { label: '6000~20000', value: 1 },
    { label: '20000~40000', value: 2 },
    { label: '40000~70000', value: 3 },
    { label: '70000以上', value: 4 },
])

const searchFormRef = ref<FormInstance>()

onMounted(() => {
    console.log(route.query)
    if (route.query.create_time) {
        memberTableData.searchParam.create_time = route.query.create_time
    }
    if (route.query.user_type) {
        memberTableData.searchParam.user_type = route.query.user_type
    }
    if (route.query.day) {
        memberTableData.searchParam.day = Number(route.query.day)
    }
    if (route.query.min_max) {
        memberTableData.searchParam.min_max = Number(route.query.min_max)
    }
    setChannelList()
    getMemberLabelAllFn()
    loadMemberList()
})

// 获取注册方式
const channelList = ref([])
const setChannelList = async () => {
    channelList.value = await (await getRegisterChannelType({})).data
}

// 获取全部标签
const labelSelectData = ref([])
const getMemberLabelAllFn = async () => {
    labelSelectData.value = await (await getMemberLabelAll()).data
}

const levelSelectData = ref([])
getMemberLevelAll().then(({ data }) => {
    levelSelectData.value = data
})

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    isReset.value = true
    loadMemberList()
}

const clearFields = () => {
    memberTableData.searchParam.day = ''
    memberTableData.searchParam.min_max = ''
}

const isReset = ref(false)
// 获取会员列表
const loadMemberList = (page: number = 1) => {
    memberTableData.loading = true
    memberTableData.page = page

    getMemberList({
        page: memberTableData.page,
        limit: memberTableData.limit,
        ...memberTableData.searchParam
    }).then(res => {
        memberTableData.loading = false
        memberTableData.data = res.data.data
        memberTableData.total = res.data.total
        if (isReset.value) {
            isSelectAllPages.value = false
            excludedIds.value = []
            currentSelectMode.value = null
            multipleSelection.value = []
        }
        if (isSelectAllPages.value && !isReset.value) {
            restoringSelection.value = true
            nextTick(() => {
                memberTableData.data.forEach((item: any) => {
                    if (!excludedIds.value.includes(item.member_id)) {
                        memberListTableRef.value?.toggleRowSelection(item, true)
                    } else {
                        memberListTableRef.value?.toggleRowSelection(item, false)
                    }
                })

                restoringSelection.value = false
            })
        }
        isReset.value = false
    }).catch(() => {
        isReset.value = false
        memberTableData.loading = false
    })
}

// 全选所有页时排除的 ID
const excludedIds = ref<number[]>([])
// 是否全选所有页
const isSelectAllPages = ref(false)

const currentSelectMode = ref<'all' | 'page' | null>(null)

// 全选当前页
const toggleChange = () => {
    restoringSelection.value = true // 加锁
    if (currentSelectMode.value === 'page') {
        isSelectAllPages.value = false
        currentSelectMode.value = null
        excludedIds.value = []
        multipleSelection.value = []
        memberListTableRef.value.clearSelection()
    } else {
        isSelectAllPages.value = false
        currentSelectMode.value = 'page'
        excludedIds.value = []
        multipleSelection.value = []
        memberTableData.data.forEach((row: any) => {
            memberListTableRef.value.toggleRowSelection(row, true)
        })
        multipleSelection.value = [...memberTableData.data]
    }
    nextTick(() => {
        restoringSelection.value = false // 解锁
    })
}

// 全选所有页
const selectAllPages = () => {
    restoringSelection.value = true // 加锁
    if (currentSelectMode.value === 'all') {
        isSelectAllPages.value = false
        currentSelectMode.value = null
        excludedIds.value = []
        multipleSelection.value = []
        memberListTableRef.value.clearSelection()
    } else {
        // memberListTableRef.value.clearSelection()
        excludedIds.value = []
        multipleSelection.value = []
        isSelectAllPages.value = true
        currentSelectMode.value = 'all'
        memberTableData.data.forEach((row: any) => {
            memberListTableRef.value.toggleRowSelection(row, true)
        })
    }
    nextTick(() => {
        restoringSelection.value = false // 解锁
    })
}
const defaultSelection = computed(() => {
    if (isSelectAllPages.value) {
        return memberTableData.data.filter((item: any) => !excludedIds.value.includes(item.member_id))
    } else {
        return multipleSelection.value
    }
})

const memberListTableRef = ref()

// 选中数据
const multipleSelection: any = ref([])
const restoringSelection = ref(false)

const handleSelectionChange = (val: any[]) => {
    if (restoringSelection.value) return // 阻止自动恢复触发逻辑

    if (isSelectAllPages.value) {
        const currentPageIds = memberTableData.data.map((item: any) => item.member_id)
        const selectedIds = val.map((item: any) => item.member_id)
        const unselected = currentPageIds.filter(id => !selectedIds.includes(id))

        excludedIds.value = Array.from(new Set([...excludedIds.value, ...unselected]))
        excludedIds.value = excludedIds.value.filter(id => !selectedIds.includes(id))
    } else {
        multipleSelection.value = val
    }
}
const selectedCount = computed(() => {
    if (isSelectAllPages.value) {
        return memberTableData.total - excludedIds.value.length
    } else {
        return multipleSelection.value.length
    }
})

// 排序处理函数
const handleSortChange = ({ prop, order }: { prop: string, order: string | null }) => {
    if (prop && order) {
        memberTableData.searchParam.order = prop
        memberTableData.searchParam.type = order === 'ascending' ? 'asc' : 'desc'
    } else {
        memberTableData.searchParam.order = ''
        memberTableData.searchParam.type = ''
    }
    loadMemberList()
}

const getBatchPayload = () => {
    if (isSelectAllPages.value) {
        return {
            is_all: 1,
            ids: excludedIds.value,
            where: {
                ...memberTableData.searchParam
            }
        }
    } else {
        return {
            is_all: 0,
            ids: multipleSelection.value.map((item: any) => item.member_id),
            where: {
                ...memberTableData.searchParam
            }
        }
    }
}

/** ***************** 批量设置-start *************************/
const batchSetLabel = () => {
    const isNoneSelected =
        (!isSelectAllPages.value && multipleSelection.value.length === 0) ||
        (isSelectAllPages.value && excludedIds.value.length === memberTableData.total)

    if (isNoneSelected) {
        ElMessage({
            type: 'warning',
            message: `${ t('batchEmptySelectedTips') }`
        })
        return
    }
    const info = getBatchPayload()
    const data = ref({
        method: 'batchSet',
        type: 'member_label',
        title: t('批量设置会员标签'),
        data: info
    })
    editMemberDialog.value?.batchSetDialogType(data.value)
    editMemberDialog.value.showDialog = true
}
// 等级
const batchSetLevel = () => {
    const isNoneSelected =
    (!isSelectAllPages.value && multipleSelection.value.length === 0) ||
    (isSelectAllPages.value && excludedIds.value.length === memberTableData.total)

    if (isNoneSelected) {
        ElMessage({
            type: 'warning',
            message: `${t('batchEmptySelectedTips')}`
        })
        return
    }
    const info = getBatchPayload()
    const data = ref({
        method: 'batchSet',
        type: 'member_level',
        title: t('批量设置会员等级'),
        data: info
    })
    editMemberDialog.value?.batchSetDialogType(data.value)
    editMemberDialog.value.showDialog = true
}
const loadMemberListReset = () => {
    isReset.value = true
    loadMemberList()
}
/** ***************** 批量设置-end *************************/
const addMemberDialog = ref<any>(null)
const editMemberDialog = ref<any>(null)
const detailMemberDialog = ref<any>(null)
const upgradeDetailDialog = ref<any>(null)

/**
 * 设置标签
 */
const setMemberLabel = (res: any) => {
    const data = ref({
        type: 'member_label',
        id: res.member_id,
        title: t('setLabel'),
        data: res
    })
    editMemberDialog.value?.setDialogType(data.value)
    editMemberDialog.value.showDialog = true
}

// 查看会员升级详情
const upgradeDetailEvent = (res: any) => {
    upgradeDetailDialog.value?.setFormData(res)
    upgradeDetailDialog.value.showDialog = true
}

/**
 * 注销
 */
const deleteEvent = (res: any) => {
    ElMessageBox.confirm(t('memberDeleteTips'), t('warning'),
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        memberDelAccount(res.member_id).then(() => {
            loadMemberList()
        })
    })
}

/**
 * 添加会员
 */
const addEvent = () => {
    addMemberDialog.value.setFormData()
    addMemberDialog.value.showDialog = true
}

/**
 * 会员详情
 */
const detailEvent = (res: any) => {
    const data = {id: res.member_id};
    detailMemberDialog.value.setFormData(data);
    detailMemberDialog.value.showDialog = true;
}

/**
 * 会员导出
 */
const exportSureDialog = ref(null)
const flag = ref(false)
const handleClose = (val: any) => {
    flag.value = val
}
const exportEvent = () => {
    flag.value = true
}
/**
 * 变更会员状态
 */
const lockMember = (row: any, status: any) => {
   let lockTips = row.status == 1 ? "确定要冻结该会员吗，冻结后该会员将无法登录？" : "确定要解冻该会员吗？";
    ElMessageBox.confirm(lockTips, t('warning'),
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        editMemberStatus({
            status,
            member_ids: [row.member_id]
        }).then((res: any) => {
            if (res.code >= 0) {
                loadMemberList()
            }
        })
    })
}

/**
 * 重置密码
 */
const resetPasswordDialog = reactive({
    visible: false,
    loading: false,
    currentMember: null as any,
    form: {
        password: '',
        confirmPassword: ''
    },
    rules: {
        password: [
            { required: true, message: t('pleaseEnterNewPassword'), trigger: 'blur' },
            { min: 6, message: t('passwordLengthTip'), trigger: 'blur' }
        ],
        confirmPassword: [
            { required: true, message: t('pleaseConfirmPassword'), trigger: 'blur' },
            {
                validator: (rule: any, value: string, callback: any) => {
                    if (value !== resetPasswordDialog.form.password) {
                        callback(new Error(t('passwordNotMatch')))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur'
            }
        ]
    }
})

// 批量上传相关
const importDialog = ref(false)
const importDialogLoading = ref(false)
/**
 * 表单数据
 */
const importData = ref({
    url: ''
})
const failList = ref([]) // 导入失败列表

// 重置数据
const initImportData = () => {
    importData.value.url = ''
    importDialogLoading.value = false
    failList.value = []
}

/**
 * 会员批量上传
 */
const importMember = () => { 
    importDialogLoading.value = true
    batchImportMember(importData.value).then((res) => {
        failList.value = res.data.fail_list || [];
        if (failList.value.length == 0) {
            importDialog.value = false;
        }
        importData.value.url = ''
        loadMemberList()
    }).finally(() => {
        importDialogLoading.value = false
    })
}

// 打开批量上传弹窗
const openImportDialog = () => {
    initImportData()
    importDialog.value = true
}

// 下载模板
const downloadTemplate = () => {
    const url = `${import.meta.env.VITE_IMG_DOMAIN || location.origin}/addon/shop/batch/batch_member.xls`
    window.open(url)
}

const resetPasswordFormRef = ref<FormInstance>()

const resetPasswordEvent = (row: any) => {
    resetPasswordDialog.currentMember = row
    resetPasswordDialog.form.password = ''
    resetPasswordDialog.form.confirmPassword = ''
    resetPasswordDialog.visible = true
}

// 确认重置密码
const confirmResetPassword = () => {
    resetPasswordFormRef.value?.validate((valid) => {
        if (valid) {
            ElMessageBox.confirm(
                t('resetPasswordConfirmTip'),
                t('warning'),
                {
                    confirmButtonText: t('confirm'),
                    cancelButtonText: t('cancel'),
                    type: 'warning'
                }
            ).then(() => {
                resetPasswordDialog.loading = true
                getMemberRechargePassword({
                    member_id: resetPasswordDialog.currentMember!.member_id,
                    password: resetPasswordDialog.form.password
                }).then((res: any) => {
                    if (res.code >= 0) {
                        ElMessage.success(t('resetPasswordSuccess'))
                        resetPasswordDialog.visible = false
                        loadMemberList()
                    }
                }).finally(() => {
                    resetPasswordDialog.loading = false
                })
            }).catch(() => {})
        }
    })
}
</script>

<style lang="scss" scoped></style>
